package com.example.wendao.view.ui.fragment;


import android.app.AlertDialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.wendao.App;
import com.example.wendao.R;
import com.example.wendao.model.entity.User;
import com.example.wendao.viewmodel.UserViewModel;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A simple {@link Fragment} subclass.
 */
public class ModifyUserInfoFragment extends Fragment {

public Button modify;
public EditText mo_username;
public EditText mo_password;
public EditText mo_birthday;
public RadioGroup mo_gender;
public RadioButton mo_male;
public RadioButton mo_female;
public Button submit;
private UserViewModel userViewModel;
public User user;
private Button back_to_login;

public Boolean un_ok;       // 用户名是否合格
public Boolean pw_ok;       // 密码是否合格
public Boolean bir;         // 生日是否合格
public Boolean flag = true;
public ModifyUserInfoFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        userViewModel = new ViewModelProvider(App.getInstance()).get(UserViewModel.class);
        View view = inflater.inflate(R.layout.fragment_modify_user_info, container, false);
        modify= view.findViewById(R.id.modify);
        mo_username= view.findViewById(R.id.mo_username);
        mo_password= view.findViewById(R.id.mo_password);
        mo_birthday= view.findViewById(R.id.mo_birthday);

        submit= view.findViewById(R.id.submit);
        back_to_login = view.findViewById(R.id.back_to_login);
        // submit.setVisibility(View.INVISIBLE);

        // 设置点击前不可编辑不可点击
        mo_username.setFocusable(true);
        mo_username.setFocusableInTouchMode(true);
        mo_password.setFocusable(true);
        mo_password.setFocusableInTouchMode(true);
        mo_birthday.setFocusable(true);
        mo_birthday.setFocusableInTouchMode(true);

        back_to_login.setOnClickListener(v -> Navigation.findNavController(view).navigateUp());

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("温馨提示：");
        builder.setMessage("亲爱的闻道道友~你可以在本页查看个人信息，本页面性别信息不可以进行修改，如需修改其他信息请点击右上角的修改按钮。因为本页面没有确认密码，所以如果道友需要修改密码请在提交前自行确认，以防记错密码无法登陆~");
        builder.setPositiveButton("确定", (dialogInterface, i) -> {});
        builder.show();
        modify.setOnClickListener(view1 -> {
            if (flag){
                User user = userViewModel.getCurrentUser();
                user.setUsername(mo_username.getText().toString());
                userViewModel.updateUser(user);
                userViewModel.setCurrentUser(user);
                AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity());
                builder2.setTitle("亲爱的闻道道友：");
                builder2.setMessage("恭喜您已经修改成功用户名啦!");
                builder2.setPositiveButton("确定", (dialogInterface, i) -> {});
                builder2.show();
                Navigation.findNavController(view).navigateUp();
            } else {
                mo_username.setFocusable(true);
                mo_username.setFocusableInTouchMode(true);
                mo_password.setFocusable(true);
                mo_password.setFocusableInTouchMode(true);
                mo_birthday.setFocusable(true);
                mo_birthday.setFocusableInTouchMode(true);
                submit.setVisibility(View.VISIBLE);
                submit.setOnClickListener(view11 -> {
                    //用户名验证
                    un_ok=false;
                    if (mo_username.getText().toString().trim().equals(""))
                    {
                        Toast.makeText(getActivity(), "用户名不能为空哦~", Toast.LENGTH_SHORT).show();}
                    else if (mo_username.length()<8||mo_username.length()>13)
                    {Toast.makeText(getActivity(), "请填写一个符合要求的用户名！", Toast.LENGTH_SHORT).show();}
                    else if (userViewModel.checkUsername(mo_username.getText().toString().trim()))
                    {Toast.makeText(getActivity(), "用户名已存在，请换一个吧！", Toast.LENGTH_SHORT).show();}
                    else un_ok=true;
                    //密码验证
                    pw_ok=false;
                    if (mo_password.getText().toString().trim().equals(""))
                    {Toast.makeText(getActivity(), "密码不能为空哦~", Toast.LENGTH_SHORT).show();}
                    else if (mo_password.length()<6||mo_username.length()>8)
                    {Toast.makeText(getActivity(), "请填写一个符合要求的密码！", Toast.LENGTH_SHORT).show();}
                    else un_ok = true;

                    // 生日验证
                    bir=false;
                    if (mo_birthday.getText().toString().trim().equals(""))
                    {
                        Toast.makeText(getActivity(), "生日不能为空哦~", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        String regex = "^(19|20)\\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$";
                        Pattern pattern = Pattern.compile(regex);
                        Matcher m = pattern.matcher(mo_birthday.getText().toString().trim());
                        boolean dateFlag = m.matches();
                        if (!dateFlag) {
                            Toast.makeText(getActivity(), "日期格式错误", Toast.LENGTH_SHORT).show();
                            return ;
                        }
                        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        formatter.setLenient(false);
                        try{
                            Date date = formatter.parse(mo_birthday.getText().toString().trim());
                            bir=true;
                        }catch(Exception e){
                            Toast.makeText(getActivity(), "日期格式错误", Toast.LENGTH_SHORT).show();
                        }
                    }
                    if (un_ok && pw_ok && bir) {
                        user.setUsername(mo_username.getText().toString().trim());
                        user.setPassword(mo_password.getText().toString().trim());
                        user.setBirthday(mo_birthday.getText().toString().trim());
                        user.setGender(userViewModel.getCurrentUser().isGender());
                        userViewModel.setCurrentUser(user);                         //返回当前用户的数据
                        userViewModel.updateUser(userViewModel.getCurrentUser());   //把用户数据写进后台
                        AlertDialog.Builder builder2 = new AlertDialog.Builder(getActivity());
                        builder2.setTitle("亲爱的闻道道友：");
                        builder2.setMessage("恭喜您已经修改成功啦!");
                        builder2.setPositiveButton("确定", (dialogInterface, i) -> {});
                    }
                });
            }
        });
        return view;
    }
}

